﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FONCREAGROINTEGRAL.Models;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace FONCREAGROINTEGRAL.Controllers
{
    public class semovienteController : Controller
    {
        public SistIntFoncreagroEntities entidades = new SistIntFoncreagroEntities();

        public static Image ResizeImage(Image srcImage, int newWidth, int newHeight)
        {
            using (Bitmap imagenBitmap = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppRgb))
            {
                imagenBitmap.SetResolution(Convert.ToInt32(srcImage.HorizontalResolution), Convert.ToInt32(srcImage.HorizontalResolution));

                using (Graphics imagenGraphics =
                        Graphics.FromImage(imagenBitmap))
                {
                    imagenGraphics.SmoothingMode =
                       SmoothingMode.AntiAlias;
                    imagenGraphics.InterpolationMode =
                       InterpolationMode.HighQualityBicubic;
                    imagenGraphics.PixelOffsetMode =
                       PixelOffsetMode.HighQuality;
                    imagenGraphics.DrawImage(srcImage,
                       new Rectangle(0, 0, newWidth, newHeight),
                       new Rectangle(0, 0, srcImage.Width, srcImage.Height),
                       GraphicsUnit.Pixel);
                    MemoryStream imagenMemoryStream = new MemoryStream();
                    imagenBitmap.Save(imagenMemoryStream, ImageFormat.Jpeg);
                    srcImage = Image.FromStream(imagenMemoryStream);
                }
            }
            return srcImage;
        }
        //
        // GET: /semoviente/

        public ActionResult IndexPadre()
        {
            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);

            string nomarete = Convert.ToString(Request.QueryString["query"]);

            var query = entidades.SEMOVIENTEs.Where(s => s.IdSemoviente > 0);

            if (!String.IsNullOrEmpty(nomarete))
            {
                query = query.Where(s => (s.Nombre).ToUpper().Contains(nomarete.ToUpper()) ||
                    s.AreteMicrochip.ToUpper().Contains(nomarete.ToUpper()));
            }

            var result = (from s in query.OrderBy(p => p.AreteMicrochip).Skip(start).Take(limit).ToList()
                          select new
                          {
                              IdSemovientePadre = s.IdSemoviente,
                              AretePadre = s.AreteMicrochip,
                              NombrePadre = s.Nombre,
                          }).ToList();

            return Json(new { grid = result, total = query.Count() }, JsonRequestBehavior.AllowGet);
        }
        //
        // GET: /semoviente/

        public ActionResult IndexMadre()
        {
            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);

            string nomarete = Convert.ToString(Request.QueryString["query"]);

            var query = entidades.SEMOVIENTEs.Where(s => s.IdSemoviente > 0);

            if (!String.IsNullOrEmpty(nomarete))
            {
                query = query.Where(s => (s.Nombre).ToUpper().Contains(nomarete.ToUpper()) ||
                    s.AreteMicrochip.ToUpper().Contains(nomarete.ToUpper()));
            }

            var result = (from s in query.OrderBy(p => p.AreteMicrochip).Skip(start).Take(limit).ToList()
                          select new
                          {
                              IdSemovienteMadre = s.IdSemoviente,
                              AreteMadre = s.AreteMicrochip,
                              NombreMadre = s.Nombre,
                          }).ToList();

            return Json(new { grid = result, total = query.Count() }, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /semoviente/

        public ActionResult IndexById(int id)
        {
            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);

            string nomarete = Convert.ToString(Request.QueryString["query"]);

            var result = entidades.INVSemovienteById(id).ToList();

            return Json(new { grid = result, total = result.Count() }, JsonRequestBehavior.AllowGet);
        }
        //
        // GET: /semoviente/

        public ActionResult IndexParents()
        {
            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);

            string nomarete = Convert.ToString(Request.QueryString["query"]);

            var query = entidades.SEMOVIENTEs.Where(s => s.IdSemoviente > 0);

            if (!String.IsNullOrEmpty(nomarete))
            {
                query = query.Where(s => (s.Nombre).ToUpper().Contains(nomarete.ToUpper()) || 
                    s.AreteMicrochip.ToUpper().Contains(nomarete.ToUpper()));
            }

            var result = (from s in query.OrderBy(p => p.AreteMicrochip).Skip(start).Take(limit).ToList()
                          select new
                          {
                              IdSemoviente = s.IdSemoviente,
                              Arete = s.AreteMicrochip,
                              Nombre = s.Nombre,
                          }).ToList();

            return Json(new { grid = result, total = query.Count() }, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /semoviente/

        public ActionResult Index()
        {
            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);
            string nombre = Convert.ToString(Request.QueryString["query"]);

            if (String.IsNullOrEmpty(nombre))
            {
                nombre = "";
            }

            var query = entidades.INVListSemovientes(nombre).ToList();

            //return Json(new { grid = query, total = query.Count() }, JsonRequestBehavior.AllowGet);

            return Json(new { grid = query.Skip(start).Take(limit), total = query.Count() }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult IndexFrm(int id)
        {
            int start = Convert.ToInt32(Request.QueryString["start"]);
            int limit = Convert.ToInt32(Request.QueryString["limit"]);
            string nombre = Convert.ToString(Request.QueryString["query"]);

            if (!String.IsNullOrEmpty(nombre))
            {
                nombre = "";
            }

            var query = entidades.INVListSemovientes(nombre).ToList().Where(s => s.IdProyectoCPD == id);

            //return Json(new { grid = query, total = query.Count() }, JsonRequestBehavior.AllowGet);

            return Json(new { grid = query.Skip(start).Take(limit), total = query.Count() }, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /semoviente/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /semoviente/Create

        //public ActionResult Create()
        //{
        //    return View();
        //} 

        //
        // POST: /semoviente/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection, HttpPostedFileBase FotoFrente, HttpPostedFileBase FotoPerfil,HttpPostedFileBase Certificado)
        {
            string strResponse = String.Empty;

            int IdEstadoSemoviente = Convert.ToInt32(Request.Form["IdEstadoSemoviente"]);
            int IdCategoria = Convert.ToInt32(Request.Form["IdCategoria"]);
            int IdUbicacion = Convert.ToInt32(Request.Form["IdUbicacion"]);
            int IdProyectoCPD = Convert.ToInt32(Request.Form["IdProyectoCPD"]);
            int IdPlan = Convert.ToInt32(Request.Form["IdPlan"]);
            int IdPersonal = Convert.ToInt32(Session["IdPersonal"].ToString());
            
            decimal Peso = Convert.ToDecimal(Request.Form["Peso"]);
            decimal Valor = Convert.ToDecimal(Request.Form["Valor"]);
            
            int TipoIngreso = Convert.ToInt32(Request.Form["TipoIngreso"]);

            try
            {
                // TODO: Add insert logic here
                var CSemoviente = new SEMOVIENTE();
                if (ModelState.IsValid)
                {
                    TryUpdateModel(CSemoviente, collection.ToValueProvider());
                    CSemoviente.FechaRegistro = DateTime.Now;
                    entidades.AddToSEMOVIENTEs(CSemoviente);
                    entidades.SaveChanges();
                    entidades.INVInsertSemoviente(CSemoviente.IdSemoviente, IdEstadoSemoviente, IdCategoria, IdUbicacion, Peso, Valor);

                    if (FotoFrente != null)
                    {
                        FotoFrente.SaveAs(Server.MapPath("~/Content/Semovientes/Fotos/Temporales/") + Path.GetFileName(FotoFrente.FileName));
                        //Image srcImage;// = new Image();// = Image.FromFile(Server.MapPath("~/Content/Semovientes/Fotos/Temporales/" + Path.GetFileName(FotoFrente.FileName)));
                        System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/Content/Semovientes/Fotos/Temporales/" + Path.GetFileName(FotoFrente.FileName)), System.IO.FileMode.Open);
                        Image srcImage = Image.FromStream(fs);
                        var ancho = srcImage.Width;
                        var alto = srcImage.Height;
                        /////Establecer ancho nuevo
                        var nuevoancho = 400;
                        var nuevoalto = (nuevoancho * alto) / ancho;
                        Image image = ResizeImage(srcImage, nuevoancho, nuevoalto);
                        image.Save(Server.MapPath("~/Content/Semovientes/Fotos/" + ("FotoFrente" + Convert.ToString(CSemoviente.IdSemoviente) + ".jpg")));

                        fs.Close();
                        System.IO.File.Delete(Server.MapPath("~/Content/Semovientes/Fotos/Temporales/") + Path.GetFileName(FotoFrente.FileName));
                    }

                    if (FotoPerfil != null)
                    {
                        FotoPerfil.SaveAs(Server.MapPath("~/Content/Semovientes/Fotos/Temporales/") + Path.GetFileName(FotoPerfil.FileName));
                        //Image srcImage = Image.FromFile(Server.MapPath("~/Content/Semovientes/Fotos/Temporales/" + Path.GetFileName(FotoPerfil.FileName)));
                        System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("~/Content/Semovientes/Fotos/Temporales/" + Path.GetFileName(FotoPerfil.FileName)), System.IO.FileMode.Open);
                        Image srcImage = Image.FromStream(fs);
                        var ancho = srcImage.Width;
                        var alto = srcImage.Height;
                        /////Establecer ancho nuevo
                        var nuevoancho = 400;
                        var nuevoalto = (nuevoancho * alto) / ancho;
                        Image image = ResizeImage(srcImage, nuevoancho, nuevoalto);
                        image.Save(Server.MapPath("~/Content/Semovientes/Fotos/" + ("FotoPerfil" + Convert.ToString(CSemoviente.IdSemoviente) + ".jpg")));

                        fs.Close();
                        System.IO.File.Delete(Server.MapPath("~/Content/Semovientes/Fotos/Temporales/") + Path.GetFileName(FotoPerfil.FileName));
                    }

                    //Guardar Certificados
                    if (Certificado != null)
                    {
                        Certificado.SaveAs(Server.MapPath("~/Content/Semovientes/Certificados/") + Convert.ToString(CSemoviente.IdSemoviente) + ".pdf");
                    }

                    strResponse = "{success: true,msg:'Registro Creado Correctamente'}";
                    return Content(strResponse);
                }

                if (TipoIngreso == 1)
                {
                    entidades.GenerarTRANSACCIONnacimientoSemovientes(IdProyectoCPD, IdPlan, Valor, DateTime.Now, IdPersonal);
                }

                strResponse = "{success: false,msg:'Fallo en la Creación'}";
                return Content(strResponse);
            }
            catch
            {
                strResponse = "{success: false,msg:'Fallo en la Creación'}";
                return Content(strResponse);
            }
        }
        
        //
        // GET: /semoviente/Edit/5
 
        //public ActionResult Edit(int id)
        //{
        //    return View();
        //}

        //
        // POST: /semoviente/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            string strResponse = String.Empty;
            try
            {
                // TODO: Add update logic here
                var eSem = entidades.SEMOVIENTEs.Single(p => p.IdSemoviente == id);
                TryUpdateModel(eSem);
                entidades.SaveChanges();
                strResponse = "{success: true,msg:'Registro Creado Correctamente'}";
                return Content(strResponse);
            }
            catch
            {
                strResponse = "{success: false,msg:'Fallo en la Creación'}";
                return Content(strResponse);
            }
        }

        //
        // GET: /semoviente/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /semoviente/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

    }
}
